import React, { PureComponent, Fragment } from "react";
import { DatePicker, message } from "antd";
import { connect } from "dva";
import moment from "moment";
import PateoStandardTable from "@/common/PateoTable/PateoStandardTable";
import styles from "./index.less";
const dateFormat = "YYYY-MM-DD";
const { RangePicker } = DatePicker;

const mock = [
  [
    { lon: 114.089316, lat: 30.450525, tid: 1666315773000, kmTotal: null },
    { lon: 114.08931, lat: 30.450526, tid: 1666315774000, kmTotal: null },
    { lon: 114.089311, lat: 30.450526, tid: 1666315781000, kmTotal: null },
  ],
  [
    { lon: 114.089319, lat: 30.450524, tid: 1666316026000, kmTotal: null },
    { lon: 114.089313, lat: 30.450522, tid: 1666316027000, kmTotal: null },
    { lon: 114.08932, lat: 30.450522, tid: 1666316037000, kmTotal: null },
    { lon: 114.089315, lat: 30.450521, tid: 1666316047000, kmTotal: null },
    { lon: 114.089313, lat: 30.450521, tid: 1666316057000, kmTotal: null },
  ],
  [
    { lon: 114.089341, lat: 30.450526, tid: 1666318259000, kmTotal: null },
    { lon: 114.089338, lat: 30.45052, tid: 1666318260000, kmTotal: null },
    { lon: 114.089336, lat: 30.450518, tid: 1666318270000, kmTotal: null },
    { lon: 114.089344, lat: 30.450523, tid: 1666318280000, kmTotal: null },
  ],
];
@connect(({ warningCar, }) => ({
  warningCar,
}))
export default class TrackList extends PureComponent {
  state = {
    totalMileage: null,
    listData: [],
    userstopDates: [],
    // endValue: [],
    startValue: moment(),
    endValue: moment(),
    endOpen: false,
    disabledOriginDate: null,
    selectedRouteList: [],
  };

  componentDidMount() {
    this.getTableData();
  }

  /**
   * 生成GUID
   * @returns string
   */
  generateGUID = () => {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
      const r = (Math.random() * 16) | 0;
      const v = c === "x" ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  };
  getTableData = () => {
    const { setDataState } = this.props;

    const { startValue, endValue } = this.state;
    let vin = sessionStorage.getItem("warning_track_vin");
    if (!endValue) {
      return;
    }
    const { dispatch } = this.props;
    this.setState({ selectedRouteList: [] });
    setDataState([]);

    dispatch({
      type: "warningCar/postObjWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/track/list",
        vin,
        beginDate: startValue
          ? startValue.format(dateFormat)
          : moment().format(dateFormat),
        endDate: endValue
          ? endValue.format(dateFormat)
          : moment().format(dateFormat),
      },
      callback: (response) => {
        if (response.statusCode === "0") {
          // this.setState({ listData: response.data })
          const data = response.data;
          // const data = {
          //   vin: "LDP35G908NG005126",
          //   mileage: "0.0",
          //   userTrackVoList: [
          //     {
          //       vin: "LDP35G908NG005126",
          //       startTime: "2022-10-21 09:29:33",
          //       endTime: "2022-10-21 09:29:41",
          //       startTimestamp: "1666315773",
          //       endTimestamp: "1666315782",
          //       eachMileage: "0.0",
          //     },
          //     {
          //       vin: "LDP35G908NG005126",
          //       startTime: "2022-10-21 09:33:46",
          //       endTime: "2022-10-21 09:34:23",
          //       startTimestamp: "1666316026",
          //       endTimestamp: "1666316064",
          //       eachMileage: "0.0",
          //     },
          //     {
          //       vin: "LDP35G908NG005126",
          //       startTime: "2022-10-21 10:10:59",
          //       endTime: "2022-10-21 10:11:28",
          //       startTimestamp: "1666318259",
          //       endTimestamp: "1666318289",
          //       eachMileage: "0.0",
          //     },
          //   ],
          // };
          const listData = data.userTrackList?.map((item) => {
            return {
              id: this.generateGUID(),
              ...item,
            };
          });
          const totalMileage = data.mileage;
          this.setState({ listData, totalMileage: totalMileage || 0  });
        } else {
          this.setState({ listData: [], totalMileage: 0 });
        }
      },
    });
  };

  handleOpenChange = (open, value) => {
    // console.log("open");
    if (open) {
      setTimeout(() => {
        window.onload = function () {
        document
          .getElementsByClassName("ant-calendar-prev-month-btn")[0]
          .addEventListener("click", () => this.handleMonthChange("month", -1));
        document
          .getElementsByClassName("ant-calendar-next-month-btn")[0]
          .addEventListener("click", () => this.handleMonthChange("month", 1));
        document
          .getElementsByClassName("ant-calendar-prev-year-btn")[0]
          .addEventListener("click", () => this.handleMonthChange("year", -1));
        document
          .getElementsByClassName("ant-calendar-next-year-btn")[0]
          .addEventListener("click", () => this.handleMonthChange("year", 1));
        }
      }, 500);

      if (value) {
        value = moment(value).format("YYYYMM");
      } else {
        value = moment(this.datepicker).format("YYYYMM");
      }

      this.getUserstopDates(value);
    }
  };

  handlePanelChange = (value, mode) => {
    value = moment(value).format("YYYYMM");
    this.getUserstopDates(value);
  };

  // // range待选变化
  // handleCalendarChange = (dates) => {
  //   console.log(dates);
  //   this.setState({
  //     disabledOriginDate: dates.length ? dates[0] : moment(),
  //   });
  // };

  handleMonthChange = (type, add) => {
    let year = document.getElementsByClassName("ant-calendar-year-select")[0]
      .text;
    year = year.substring(0, year.length - 1);
    let month = document.getElementsByClassName("ant-calendar-month-select")[0]
      .text;
    month = month.substring(0, month.length - 1);
    if (type === "year") {
      year = parseInt(year) + add;
    }
    if (type === "month") {
      if (month === "12" && add === 1) {
        month === "1";
        year = parseInt(year) + 1;
      } else if (month === "1" && add === -1) {
        month === "12";
        year = parseInt(year) - 1;
      } else {
        month = parseInt(month) + add;
      }
      month = "" + month;
    }

    month = month.length === 1 ? "0" + month : month;
    let value = year + month;
    this.getUserstopDates(value);
  };
  getUserstopDates = (month) => {
    let vin = sessionStorage.getItem("warning_track_vin");
    const { dispatch } = this.props;
    dispatch({
      type: "warningCar/getDataWithRes",
      payload: {
        url: "/electricfence/getuserstopdates",
        vin,
        month: month,
      },
      callback: (response) => {
        if (response.statusCode === "0") {
          // const dates = [...this.state.userstopDates, ...(response.data || [])];
          // const newDates = dates.filter((value, index, self) => {
          //   return self.indexOf(value) === index;
          // });
          // this.setState({ userstopDates: newDates });
          this.setState({ userstopDates: response.data });
        }
      },
    });
  };

  bd_decrypt = (lon, lat) => {
    let X_PI = (Math.PI * 3000.0) / 180.0;
    let x = lon - 0.0065;
    let y = lat - 0.006;
    let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI);
    let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI);
    let gg_lng = z * Math.cos(theta);
    let gg_lat = z * Math.sin(theta);
    return { longitude: gg_lng, latitude: gg_lat };
  };

  getRoute = (startTime, endTime, index) => {
    let vin = sessionStorage.getItem("warning_track_vin");
    const { dispatch, initMap, setDataState } = this.props;
    return new Promise((resolve, reject) => {
      dispatch({
        type: "warningCar/getDataWithRes",
        payload: {
          url: "/electricfence/getuserstopdetail",
          vin,
          startTime: startTime,
          endTime: endTime,
        },
        callback: (response) => {
          if (response.statusCode === "0") {
            if (response.data && response.data.length > 0) {
              let list = [];
              // // TODO: mock轨迹
              // mock[index].map((item) => {
              response.data.map((item) => {
                let l = [];
                let obj = this.bd_decrypt(item.lon, item.lat);
                l.push(Number(obj.longitude));
                l.push(Number(obj.latitude));
                list.push(l);
              });
              resolve(list);
            } else {
              message.error("数据不存在");
            }
          } else {
            message.error("查询轨迹点失败，请稍后再试");
          }
        },
      });
    });
    return new Promise((resolve, reject) => {
      dispatch({
        type: "retailPostAndUser/pageGetByCode",
        payload: {
          url: "/third/credit/gettrajectoryroute",
          vin,
          starttime: startTime,
          endtime: endTime,
        },
        callback: (response) => {
          if (response.statusCode === "200") {
            if (response.data && response.data.length > 0) {
              let list = [];
              // // TODO: mock轨迹
              // mock[index].map(item => {
              response.data.map((item) => {
                let l = [];
                let obj = this.bd_decrypt(item.lon, item.lat);
                l.push(Number(obj.longitude));
                l.push(Number(obj.latitude));
                list.push(l);
              });
              resolve(list);
            } else {
              message.error("数据不存在");
            }
          } else {
            message.error("查询轨迹点失败，请稍后再试");
          }
        },
      });
    });
  };

  disabledStartDate = (startValue) => {
    // 前后30天且近一年内
    const { endValue } = this.state;
    if (!endValue) {
      return (
        startValue &&
        (startValue < moment().subtract(1, "years") ||
          startValue > moment().endOf("day"))
      );
    }
    return (
      startValue &&
      (startValue < moment(endValue).subtract(30, "days") ||
        startValue > moment(endValue))
    );
  };
  disabledEndDate = (endValue) => {
    const { startValue } = this.state;
    if (!startValue) {
      return (
        endValue &&
        (endValue < moment().subtract(1, "years") ||
          endValue > moment().endOf("day"))
      );
    }
    return (
      endValue &&
      (endValue > moment(startValue).add(30, "days") ||
        endValue < moment(startValue))
    );
  };
  onStartChange = (value) => {
    this.onChange("startValue", value);
  };
  onChange = (field, value) => {
    this.setState(
      {
        [field]: value,
      },
      () => {
        this.getTableData();
      }
    );
  };
  onEndChange = (value) => {
    this.onChange("endValue", value);
  };
  handleStartOpenChange = (open) => {
    if (!open) {
      this.setState({ endOpen: true });
    }
    this.handleOpenChange(open, this.state.startValue);
  };

  handleEndOpenChange = (open) => {
    this.setState({ endOpen: open });
    this.handleOpenChange(open, this.state.endValue);
  };
  render() {
    let vin = sessionStorage.getItem("warning_track_vin");
    const { loading, setDataState, selectedTrackData } = this.props;
    const {
      totalMileage,
      listData,
      userstopDates,
      startValue,
      endValue,
      endOpen,
      selectedRowKeys,
      selectedRouteList,
    } = this.state;

    const columns = [
      {
        title: "序号",
        width: 50,
        dataIndex: "num",
        render: (text, record, index) => {
          return index + 1;
        },
      },
      {
        title: "起止时间",
        dataIndex: "time",
        width: 200,
        onCell: () => {
           return {
            style: {
               wordBreak: 'keep-all',
               whiteSpace: 'pre-wrap',
               overflowWrap: 'break-word',
             }
         }
         },
        render: (text, record) => {
          return `${record.startTime}-${record.endTime}`;
        },
      },
      {
        title: "里程（KM）",
        dataIndex: "eachMileage",
      },
    ];
    const calcList = (selectedRows, oldRowkeys, selectedKeys) => {
      // const routeList = cloneDeep(selectedRouteList);
      return new Promise((resolve, reject) => {
        const add = selectedRows.filter(
          (item) => oldRowkeys.indexOf(item.id) == -1
        ); // 对比原始数据新增的数据
        add.forEach((row, index) => {
          this.getRoute(row.startTimestamp, row.endTimestamp, index).then(
            (singleLineData) => {
              if (singleLineData) {
                selectedRouteList.push({
                  lineId: row.id,
                  lineData: singleLineData,
                });
              }
              const newList = selectedRouteList.filter(
                (item) => selectedKeys.indexOf(item.lineId) !== -1
              );
              this.setState({ selectedRouteList: newList }, () => {
                resolve(newList);
              });
            }
          );
        });
      });
    };

    const tableProps = {
      title: (data) => {
        // const sum = data.reduce((perv, cur) => {
        //   return perv + parseFloat(cur.eachMileage || '0')
        // }, 0)
        return `总里程（KM）：${totalMileage}`;
      },
      columns,
      dataSource: listData,
      rowClassName: (record, index) =>
        index === this.state.activeIndex ? styles.active : "",
      size: "small",
      loading,
      pagination: false,
      // onRowClick: (record, index) => {
      //   this.setState({ activeIndex: index });
      //   selectedTrackData(record);
      // },
      onRow:(record, index) => {
        return {
            onClick: _ => { 
              this.setState({ activeIndex: index });
              selectedTrackData(record);
             }, // 点击行
                };
    },
    rowSelection: {
      onChange: (selectedKeys, selectedRows) => {
        console.log(
          `selectedRowKeys: ${selectedKeys}`,
          "selectedRows: ",
          selectedRows
        );
        const oldRowkeys = selectedRouteList.map((item) => item.lineId);
        if (selectedRows.length > 0) {
          if (selectedKeys.length > oldRowkeys.length) {
            // 新增勾选
            calcList(selectedRows, oldRowkeys, selectedKeys).then((data) => {
              setDataState(data);
            });
          } else {
             // 取消勾选
             this.setState({ activeIndex: null });
            const add = selectedRows.filter(
              (item) => oldRowkeys.indexOf(item.id) == -1
            ); // 对比原始数据新增的数据
            if(add.length > 0){
              calcList(selectedRows, oldRowkeys, selectedKeys).then((data) => {
                setDataState(data);
              });
            }else{
            const newList = selectedRouteList.filter((item) => {
              return selectedKeys.indexOf(item.lineId) > -1;
            });
            setDataState(newList);
             }
          }
        } else {
          setDataState([]);
        }
      },
      hideDefaultSelections: true,
    },
      rowKey: (record) => record.id,
      scroll: { y: 300 },
    };

    return (
      <Fragment>
        <span>选择日期：</span>
        {/* <DatePicker
          ref={datepicker => this.datepicker = datepicker}
          defaultValue={moment()}
          format={dateFormat}
          onChange={this.getTableData}
          allowClear={false}
          value={endValue}
          style={{ width: 200, marginBottom: 20 }}
          onOpenChange={this.handleOpenChange}
          onPanelChange={this.handlePanelChange}
          dateRender={current => {
            const style = {}
            for (let i in userstopDates) {
              if (current.format('YYYY-MM-DD') === userstopDates[i]) {
                style.border = '1px solid #1890ff'
                style.borderRadius = '50%'
              }
            }
            return (
              <div className="ant-picker-cell-inner" style={style}>
                {current.date()}
              </div>
            )
          }}
        /> */}
        <DatePicker
          disabledDate={this.disabledStartDate}
          format="YYYY-MM-DD"
          value={startValue}
          placeholder="开始日期"
          onChange={this.onStartChange}
          onOpenChange={this.handleStartOpenChange}
          dateRender={(current) => {
            const style = {};
            for (let i in userstopDates) {
              if (current.format("YYYY-MM-DD") === userstopDates[i]) {
                style.border = "1px solid #1890ff";
                style.borderRadius = "50%";
              }
            }
            return (
              <div className="ant-calendar-date" style={style}>
                {current.date()}
              </div>
            );
          }}
        />
        <DatePicker
          disabledDate={this.disabledEndDate}
          format="YYYY-MM-DD"
          value={endValue}
          placeholder="结束日期"
          onChange={this.onEndChange}
          open={endOpen}
          onOpenChange={this.handleEndOpenChange}
          dateRender={(current) => {
            const style = {};
            for (let i in userstopDates) {
              if (current.format("YYYY-MM-DD") === userstopDates[i]) {
                style.border = "1px solid #1890ff";
                style.borderRadius = "50%";
              }
            }
            return (
              <div className="ant-calendar-date" style={style}>
                {current.date()}
              </div>
            );
          }}
        />
        <div className={styles.customer}>
          <PateoStandardTable
            tableProps={tableProps}
            fetchUrl="warningCar/postObjWithRes"
            parameterUrl="/mscreditbusiness/vehicle/track/list"
            formValues={{ vin }}
          />
        </div>
      </Fragment>
    );
  }
}
